package io.p2p.stream.p2pstun.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.stun.handler.StunBaseHandler;
import io.p2p.stream.stun.model.StunSharedModel;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;

@Slf4j
public class NatCheckHandler implements StunBaseHandler {
    public static final String commandType = "natCheck";

    @Override
    public void process(ChannelHandlerContext ctx, InetSocketAddress remoteAddress, JSONObject buffer) {
        String remoteAddrStr = remoteAddress.toString();

        String[] remoteAddr = remoteAddrStr.split(":");

        String clientIp = remoteAddr[0].replace("/","");
        int clientPort = Integer.parseInt(remoteAddr[1]);

        log.info("Received Client JSON data: {} at IP:{},Port:{}",buffer.toJSONString(),clientIp,clientPort);

        String subType = buffer.getString("subType");
        if("step1".equals(subType)){
            buffer.put("checked","false");
            buffer.put("step","step1");
            buffer.put("type","natCheckAck");
            buffer.put("localIP",clientIp);
            buffer.put("localPort",clientPort);
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buffer.toJSONString().getBytes()),remoteAddress));

            buffer.put("type","natCheck");
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buffer.toJSONString().getBytes()),
                    new InetSocketAddress(StunSharedModel.mainServerFirstIP, StunSharedModel.mainServerFirstPort)));
        }
    }
}
